//
//  PreferredViewController.m
//  MobileShoppingMall
//
//  Created by 冯传昌 on 2021/4/14.
//  Copyright © 2021 冯传昌. All rights reserved.
//

#import "PreferredViewController.h"

#import "PreferredHeaderView.h"

#import "PreferredCollectionViewCell.h"

#import "MainPageHeaderModel.h"

#import "MainPageGoodsModel.h"

@interface PreferredViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>

//瀑布流view
@property (nonatomic,strong) UICollectionView *collectionV;
//头部视图
@property (nonatomic,strong) PreferredHeaderView *headerV;

@property (nonatomic,strong) GeneralNavSearchView *topSearchView;

@property (nonatomic,strong) NSMutableArray *dataSourceArr;//数据源数组
@property (nonatomic,assign) NSInteger currentPage;//当前分页  初始值 1

@property (nonatomic,assign) BOOL isRefreshing;//当前页面是否正在刷新

@end

@implementation PreferredViewController

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self loadHeaderData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isRefreshing = NO;
    self.currentPage = 1;
    self.dataSourceArr = [NSMutableArray array];
    [self initUI];
    [self getNewData];
}
#pragma mark - data
-(void)loadHeaderData{
    WEAKSELF(self);
    NSMutableArray *goodTypesArr = [NSMutableArray array];
    NSMutableArray *bannerArr = [NSMutableArray array];
    [NetWorkingShop getPreferredShopInfoWithSuccessBlock:^(id  _Nonnull responseObj) {
        NSDictionary *data = responseObj[@"data"];
        NSArray *types = data[@"types"];
        NSArray *banners = data[@"productcarouses"];
        for (NSDictionary *dic in types) {
            MainPageHeaderModel *model = [MainPageHeaderModel mj_objectWithKeyValues:dic];
            model.Id = [[dic objectForKey:@"id"] integerValue];
            [goodTypesArr addObject:model];
        }
        for (NSDictionary *dic in banners) {
            MainPageHeaderModel *model = [MainPageHeaderModel mj_objectWithKeyValues:dic];
            model.Id = [[dic objectForKey:@"id"] integerValue];
            [bannerArr addObject:model];
        }
        weakSelf.headerV.bannerSourceArr = bannerArr;
        weakSelf.headerV.goodTypesArr = goodTypesArr;
    }];
}
-(void)getNewData{
    [NetWorkingShop getPreferredShopListWithPage:1 WithSuccessBlock:^(id  _Nonnull responseObj) {
        self.dataSourceArr = [NSMutableArray array];
        NSDictionary *data = responseObj[@"data"];
        NSArray *records = data[@"records"];
        for (NSDictionary *dic in records) {
            MainPageGoodsModel *model = [MainPageGoodsModel mj_objectWithKeyValues:dic];
            model.ID = [dic[@"id"] integerValue];
            [self.dataSourceArr addObject:model];
        }
        [self.collectionV reloadData];
        [self delayLoadRefreshStatus];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self delayLoadRefreshStatus];
    });
}
-(void)getMoreData{
    [NetWorkingShop getPreferredShopListWithPage:self.currentPage WithSuccessBlock:^(id  _Nonnull responseObj) {
        NSDictionary *data = responseObj[@"data"];
        NSArray *records = data[@"records"];
        for (NSDictionary *dic in records) {
            MainPageGoodsModel *model = [MainPageGoodsModel mj_objectWithKeyValues:dic];
            model.ID = [dic[@"id"] integerValue];
            [self.dataSourceArr addObject:model];
        }
        [self.collectionV reloadData];
        [self delayLoadRefreshStatus];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self delayLoadRefreshStatus];
    });
}
//延迟刷新
-(void)delayLoadRefreshStatus{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.collectionV.mj_header endRefreshing];
        [self.collectionV.mj_footer endRefreshing];
        self.isRefreshing = NO;
    });
}
- (void)setIsRefreshing:(BOOL)isRefreshing{
    _isRefreshing = isRefreshing;
    [self.view setUserInteractionEnabled:!_isRefreshing];
    self.collectionV.scrollEnabled = !_isRefreshing;
}
#pragma mark - UI
-(void)initUI{
    [self initPreferredHeaderView];
    [self loadCollectionView];
    
    [self.view addSubview:self.topSearchView];
    [self.view bringSubviewToFront:self.topSearchView];
    
    self.collectionV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (self.isRefreshing == NO) {
            self.isRefreshing = YES;
            self.currentPage = 1;
            [self.collectionV.mj_header beginRefreshing];
            [self getNewData];
        }
    }];
    self.collectionV.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.isRefreshing == NO) {
            self.isRefreshing = YES;
            self.currentPage = self.currentPage + 1;
            [self.collectionV.mj_footer beginRefreshing];
            [self getMoreData];
        }
    }];
}
//headerView  提前加载header
-(void)initPreferredHeaderView{
    WEAKSELF(self);
    self.headerV = [[PreferredHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 120)];
    [self.headerV setUpdateHeightBlock:^(CGFloat height) {
        weakSelf.headerV.height = height;
    }];
}
//加载collectionView 头部视图
-(void)loadCollectionView{
    self.collectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, -kHeight_StatusBar-5, ScreenWidth, ScreenHeight - kHeight_TabBar + kHeight_StatusBar + 5) collectionViewLayout:[self getCollectionLayout]];
    self.collectionV.delegate = self;
    self.collectionV.dataSource = self;
    self.collectionV.backgroundColor = MainBackColor;
    [self.view addSubview:self.collectionV];
    [self.collectionV registerClass:[PreferredCollectionViewCell class] forCellWithReuseIdentifier:@"PreferredCollectionViewCell"];
    [self.collectionV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
}
//获取collectionView layout
-(UICollectionViewFlowLayout *)getCollectionLayout{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((ScreenWidth-12)/2-10, ((ScreenWidth-12)/2-10)*1.7);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.headerReferenceSize = CGSizeMake(ScreenWidth, self.headerV.height);
    return layout;
}
#pragma mark - lazy
- (GeneralNavSearchView *)topSearchView{
    if (!_topSearchView) {
        _topSearchView = [[GeneralNavSearchView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, kHeight_NavBar)];
        _topSearchView.alpha = 0;
        
        [_topSearchView setShowMenuBlock:^{
        }];
    }
    return _topSearchView;
}
#pragma mark - UICollectionViewDelegate
//collectionview  header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        [headerView addSubview:self.headerV];
        return headerView;
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(((ScreenWidth-12)/2-10), ((ScreenWidth-12)/2-10)*1.7);
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MainPageGoodsModel *model = self.dataSourceArr[indexPath.row];
    static NSString * CellIdentifier = @"PreferredCollectionViewCell";
    PreferredCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.model = model;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    MainPageGoodsModel *model = self.dataSourceArr[indexPath.row];
    GoodsDetailsViewController *vc = [[GoodsDetailsViewController alloc] init];
    vc.goodsModel = model;
    vc.goodsID = model.ID;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y > kHeight_NavBar) {
        self.topSearchView.alpha = 1;
    }else if (scrollView.contentOffset.y <= 0 ){
        self.topSearchView.alpha = 0;
    }else{
        self.topSearchView.alpha = scrollView.contentOffset.y/kHeight_NavBar;
    }
}

@end
